import {
  login,
} from '@/api/user'
import {
  delCookie
} from '@/utils/tools'

const user = {
  state: {
    loginInfo: {},
    isLogin: false
  },
  mutations: {
    SET_LOGIN(state, loginInfo) {
      state.loginInfo = loginInfo
    },
    SET_LOGIN_STATE(state, login) {
      state.isLogin = login
    }
  },
  actions: {
    async login({
      dispatch,
      commit,
      rootState
    }, {
      userForm,
      keepUser
    }) {
      const result = await login(userForm)
      const userData = Object.assign({}, userForm)

      // 删除密码，不保存在本地
      delete userData.password

      if (result) {
        try {
          await dispatch('setAsyncRouter')
        } catch (error) {
          throw error || new Error('登录失败')
        }
      } else {
        throw new Error('登录失败')
      }
    },
    restoreFromSession({
      dispatch,
      commit
    }) {
      commit('SET_LOGIN_STATE', true)
    }
  }
}

export default user